import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import WangEditor from "@/components/WangEditor";
import { ProForm, ProFormInstance } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, message } from "antd";
import { useEffect, useRef, useState } from "react";

interface Props {
	getDataApi?: any;
	saveApi?: any;
	name?: string;
	btnStyles?: any;
	chapterId?: number | string;
	onValueChange?: (values: any) => void;
	onIsLoading?: (values: boolean) => void;
	setRichTextIsChange: (values: boolean) => void;
}

export default (props: Props) => {
	const { getDataApi, saveApi, name, btnStyles, chapterId, onValueChange, onIsLoading, setRichTextIsChange } = props;
	const { loading, runAsync, data } = useRequest(getDataApi, { manual: true });
	const { loading: saveLoading, runAsync: saveRunAsync } = useRequest(saveApi, { manual: true });
	const formRef = useRef<ProFormInstance>();

	useEffect(() => {
		if (!chapterId) return;
		runAsync({ chapterId }).then((res: any) => {
			formRef.current?.setFieldsValue(res?.data);
		});
	}, [chapterId]);

	useEffect(() => {
		onIsLoading && onIsLoading(loading);
	}, [loading]);

	const handleSubmit = () => {
		formRef.current?.validateFieldsReturnFormatValue?.().then(values => {
			if (data?.data?.[name] === values?.[name]) return message.success("保存成功");
			saveRunAsync({
				...data?.data,
				...values,
				chapter_desc: "1"
			}).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success("保存成功");
					setRichTextIsChange(false);
				}
			});
		});
	};

	const handleValueChange = (values: any) => {
		// console.log(values.chapter_content, "<==============values1");
		// console.log(data?.data?.chapter_content, values.chapter_content !== data?.data?.chapter_content, "<==============values2");
		// if (values.chapter_content === undefined) {
		// 	runAsync({ chapterId }).then((res: any) => {
		// 		formRef.current?.setFieldsValue(res?.data);
		// 	});
		// }
		if (values.chapter_content !== data?.data?.chapter_content) {
			onValueChange && onValueChange(values);
		}
	};

	return (
		// <Loading isHeight100 loading={loading || saveLoading}>
		<ProForm formRef={formRef} submitter={false} style={{ height: "100%" }} onValuesChange={handleValueChange}>
			<ProForm.Item name={name} rules={[{ required: true, message: "请输入内容" }]} style={{ height: "100%" }}>
				<WangEditor isNeedMenu={true} />
			</ProForm.Item>
			<div style={{ padding: "24px", display: "flex", justifyContent: "center", ...btnStyles }}>
				<Button type="primary" onClick={handleSubmit}>
					保存
				</Button>
			</div>
		</ProForm>
		// </Loading>
	);
};
